package com.ykwep.web.server;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import com.ykwep.web.server.data.Page;

public class PagesServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(PagesServlet.class
			.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		if (req.getParameter("page_id") != null) {

			Long pageId = new Long(req.getParameter("page_id"));
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			Page i = pm.getObjectById(
					Page.class, pageId);

			
			try {
				i.setContent(req.getParameter("content"));
				i.setPublished(req.getParameter("published")!=null);
				i.setTitle(req.getParameter("title"));
				i.setName(req.getParameter("name"));
				//i.setDate(new Date());
			} finally {
				pm.close();
			}
			resp.sendRedirect("/admin/edit_pages.jsp");
		} else {

			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();

			String content = req.getParameter("content");
			Date date = new Date();
			Page i = new Page(user, content, date);
			i.setName(req.getParameter("name"));
			i.setTitle(req.getParameter("title"));
			i.setPublished(req.getParameter("published")!=null);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				pm.makePersistent(i);
			} finally {
				pm.close();
			}
		}
		resp.sendRedirect("/admin/edit_pages.jsp");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		if (req.getParameter("page_id") == null) {
			resp.sendRedirect("/admin/edit_pages.jsp");
			return;
		}

		Long pageId = new Long(req.getParameter("page_id"));


		if (req.getParameter("delete") != null) {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Page i = pm.getObjectById(
					Page.class, pageId);
			
			try {
				pm.deletePersistent(i);
			} finally {
				pm.close();
			}

		}
		
		resp.sendRedirect("/admin/edit_pages.jsp");

	}
}